//
//  ViewController.m
//  ShortcutPrj
//
//  Created by ShaoHong Wen on 8/20/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "ViewController.h"
#import "GTMBase64.h"
#import "AppDelegate.h"
#define INPUT_W 200
#define INPUT_H 30
#define BTN_W 150
#define BTN_H 40

@interface ViewController ()

@end


@implementation ViewController
-(void)openURL:(NSString*)url{
    [[UIApplication sharedApplication]openURL:[NSURL URLWithString:url]];
}
-(void)onReceiveData:(CFReadStreamRef)stream type:(CFStreamEventType)type client:(SocketClient *)client{
    unsigned char buf[1024];
    CFIndex idx=CFReadStreamRead(stream, buf, 1024*100);
    buf[idx]=0;
    NSLog(@"receive data len:%d,data:%s",(int)idx,buf);
}
-(void)onResponseData:(CFWriteStreamRef)stream type:(CFStreamEventType)type client:(SocketClient *)client{
    NSAutoreleasePool *pool=[[NSAutoreleasePool alloc]init];
    NSString *rdata=[self createResponseData];
    NSMutableString *res=[[NSMutableString alloc]init];
    [res appendString:@"HTTP/1.1 200 OK\r\n"];
    [res appendString:@"Cache-Control:no-cache\r\n"];
    [res appendString:@"Expires:0\r\n"];
    [res appendString:@"Pragma:no-cache\r\n"];
    [res appendString:@"Connection:Keep-Alive\r\n"];
    [res appendString:@"Content-Type:text/html;charset=UTF-8\r\n"];
    [res appendString:@"Connection:Keep-Alive\r\n"];
    [res appendString:@"Server:ShortcutServer\r\n"];
    [res appendFormat:@"Content-Length:%d\r\n\n",[rdata length]];
    [res appendFormat:@"%@",rdata];
    const char* data=[res UTF8String];
    CFWriteStreamWrite(stream, (unsigned char*)data, strlen(data));
    [res release];
    [client close];
    [pool release];
}
-(void)onAcceptConnect:(SocketClient *)client builder:(SocketBuilder *)builder{
    client.delegate=self;
    NSLog(@"accept one client");
}
-(void)startServer:(id)sender{
    if(builder){
        return;
    }
    builder=[[SocketBuilder alloc]initWithPort:80];
    if(![builder isValid]){
        NSLog(@"initial socket builder faild.");
        [builder release];
        builder=nil;
        return;
    }
    builder.delegate=self;
    [builder addToLoop];
}
-(NSString *)createResponseData{
    NSString *icon =[GTMBase64 stringByEncodingData:UIImagePNGRepresentation([UIImage imageNamed:@"icon.png"])];
    icon=[@"data:image/png;base64," stringByAppendingString:icon];
    NSError *error;
    NSString *temp=[NSString stringWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"Template" ofType:@"html"] encoding:NSUTF8StringEncoding error:&error];
    NSString *data=[[[temp stringByReplacingOccurrencesOfString:@"${icon}" withString:icon]stringByReplacingOccurrencesOfString:@"${title}" withString:title.text]stringByReplacingOccurrencesOfString:@"${address}" withString:input.text];
    NSString *rdata=[NSString stringWithFormat:@"<head><meta http-equiv=\"refresh\" content=\"0;url=data:text/html;charset=UTF-8,%@\" /></head>",[data stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding ]];
    NSLog(@"rdata:%@",rdata);
    return rdata;
}
-(void)createShortcut:(id)sender{
    NSAutoreleasePool *pool=[[NSAutoreleasePool alloc]init];
    [AppDelegate appDelegate].responseData=[self createResponseData];
    [self performSelector:@selector(openURL:) withObject:@"http://localhost:60000/"];
    [pool release];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    UIImageView *iv=[[UIImageView alloc]initWithFrame:CGRectMake((self.view.frame.size.width-INPUT_W)/2-45, 25, 40, 40)];
    iv.image=[UIImage imageNamed:@"icon.png"];
    [self.view addSubview:iv];
    [iv release];
    //
    input=[[UITextField alloc]initWithFrame:CGRectMake((self.view.frame.size.width-INPUT_W)/2,30, INPUT_W, INPUT_H)];
    input.text=@"http://www.baidu.com";
    input.keyboardType=UIKeyboardTypeDefault;
    input.borderStyle=UITextBorderStyleRoundedRect;
    [self.view addSubview:input];
    //
    title=[[UITextField alloc]initWithFrame:CGRectMake((self.view.frame.size.width-INPUT_W)/2,input.frame.origin.y+input.frame.size.height+20, INPUT_W, INPUT_H)];
    title.text=@"百度";
    title.keyboardType=UIKeyboardTypeDefault;
    title.borderStyle=UITextBorderStyleRoundedRect;
    [self.view addSubview:title];
    //
    UIButton *btn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn.frame=CGRectMake((self.view.frame.size.width-BTN_W)/2, input.frame.origin.y+input.frame.size.height+120, BTN_W, BTN_H);
    [btn setTitle:@"Create Shortcut" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(createShortcut:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    //
    UIButton *btn2=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn2.frame=CGRectMake((self.view.frame.size.width-BTN_W)/2, btn.frame.origin.y+btn.frame.size.height+80, BTN_W, BTN_H);
    [btn2 setTitle:@"Start Server" forState:UIControlStateNormal];
    [btn2 addTarget:self action:@selector(startServer:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn2];
    //
	// Do any additional setup after loading the view, typically from a nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}
-(void)dealloc{
    if(builder){
        [builder release];
        builder=nil;
    }
    if(input){
        [input release];
        input=nil;
    }
    if(title){
        [title release];
        title=nil;
    }
    [super dealloc];
}
@end
